Working with Regular Expression in VBScript

VBScripts, Perl scripts are highly useful for automating some of routine tasks. When dealing with data logs, processing data regulary these scripts are highly useful. Regular expressions are the heart of dataprocessing, we cannot imagine data processing without it.

VBScript has got an object called RegExp

Initialize the object with

  1. Regular Expression Pattern
  2. Ignore the case (for most cases)
  3. Select Exhaustive Search

Now search the input text with above Regex Object

 

Now lets extract id of a megaupload URL

Dim url : url ="www.megaupload.com/watch?v=AXZYQM6"
id = extractID( url, "[A-Z]+$")
Function extractID( text, pattern )
  'First build regular expression box
 Dim Regex, Matches
 
 Set Regex = new RegExp 'Create Regular Expression object
 Regex.Pattern = pattern 'Apply pattern to Regex object
 Regex.Global = True  'Search all the occurances
 
 Set Matches = Regex.Execute( text ) 'Execute the text on the regular expression obj and retreive the list
 
 
 Dim i
 For i = 0 To Matches.Count
  WScript.Echo Matches(i)
 Next

 ExtractMatch = Matches(0)

End Function

Now We lets consider a practical example to stripping of HTML elements in a text
We shall you Repace() in RegExp object to replace a text having HTML element pattern with nothing.
HTML elements are like <abcxyz>, so Pattern would be “<+>”.

Function stripHTMLtags(HTMLstring)
Set RegularExpressionObject = New RegExp
With RegularExpressionObject
.Pattern = ""
.IgnoreCase = True
.Global = True
End With

stripHTMLtags = RegularExpressionObject.Replace(HTMLstring, "")
Set RegularExpressionObject = nothing

End Function

Lovely and easy right….just create a regex object and specify pattern then execute it on a text string.

About Uma Mahesh

A Creator/Equilizer. Creator/Equalizers are catalysts for positive, well-organized change. They never settle for the status quo. Instead, they see the opportunity for innovation in the processes that others have long taken for granted. They respect what's already operating, but they can't help but want to improve upon it. Their special combination provides innovation tempered with profound logic. They have incredible discernment. Should their efforts fail, they are unhesitating in accepting responsibility. They don't wallow in self-pity but rather see these missed attempts as critical steps on the path to success.
This entry was posted in Articles. Bookmark the permalink.

1 Response to Working with Regular Expression in VBScript

Leave a comment